package com.servlet;

import com.dao.SqlConnection;
import com.entity.Users;
import com.wf.captcha.utils.CaptchaUtil;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/login.html");
        requestDispatcher.forward(req,resp);
    }

    public SqlConnection sqlConnection = new SqlConnection();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String captcha = req.getParameter("captcha");


        boolean ver = CaptchaUtil.ver(captcha, req);
        if (!ver){
            CaptchaUtil.clear(req);
            System.out.println("验证码错误");
            resp.sendRedirect(req.getContextPath() + "/error");
        }else{
            System.out.println("username = " + username);
            System.out.println("password = " + password);
            // 从表单中获取的用户名和密码与预定义的用户名和密码进行比较
            if (username != null && password != null ) {
                Users users = sqlConnection.selectByUsernameAndPassword(username, password);
                if (users == null){
                    System.out.println("登录失败");
                    resp.sendRedirect(req.getContextPath() + "/error");
                }else {
                    System.out.println("登录成功");
                    resp.sendRedirect(req.getContextPath() + "/index");
                }
            } else {
                System.out.println("账户和密码不能为空");
                resp.sendRedirect(req.getContextPath() + "/error");
            }
        }

    }
}